<?php

namespace App\Kuafu\Common\Log;

use Illuminate\Log\ParsesLogConfiguration;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Processor\IntrospectionProcessor;
use Monolog\Processor\ProcessIdProcessor;

class CustomLogger
{
    use ParsesLogConfiguration;
    public static $logName = 'log';

    public function invoke(array $config)
    {
        $monolog = new Logger($config['driver']);
        $format  = "[%extra.datetime%] [%extra.process_id%] %level_name% : %message% : %context%\n";

        $monolog->pushHandler(
            $logHandler = new StreamHandler(
                $config['path'] . "/" . static::$logName . "-" . date("Y-m-d") . ".log", $config['level']
            )
        );
        $logHandler->setFormatter(
            $formatter = new LineFormatter($format, null, true, true)
        );

        $logHandler->pushProcessor(new ProcessIdProcessor());
        $logHandler->pushProcessor(new IntrospectionProcessor());
        $logHandler->pushProcessor(new ErrorProcessor());

        $logHandler->pushProcessor(function ($record) {
            $record['extra']['datetime'] = $record['datetime']->format('Y-m-d H:i:s');
            return $record;
        });

        $formatter->includeStackTraces();
        return $monolog;
    }

    protected function getFallbackChannelName()
    {
        // TODO: Implement getFallbackChannelName() method.
    }
}
